﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Windows.Forms;
using SilverFernCheckerCore.Helpers;
using SilverFernCheckerCore.Settings;

namespace SilverFernChecker
{
    public partial class ServiceForm : Form
    {
        private Settings _settings;
        private bool _canClose = false;
        public ServiceForm()
        {
            InitializeComponent();
            _settings = new Settings();
            serviceController1.ServiceName = _settings.ServiceName;
            
            if (!EventLog.SourceExists(_settings.EventLogName))
            {
                EventLog.CreateEventSource(_settings.EventLogName, _settings.EventLogName);
            }
            eventLog1.Log = _settings.EventLogName;
            eventLog1.Source = _settings.EventLogName;
            eventLog1.EnableRaisingEvents = true;
            eventLog1.EntryWritten += new System.Diagnostics.EntryWrittenEventHandler(eventLog1_EntryWritten);
            Application.Idle += new EventHandler(Application_Idle);
        }


        void ReloadEvents()
        {
            bsEvents.DataSource = eventLog1.Entries.Cast<EventLogEntry>().Select(p => new
                                                                                          {
                                                                                              Id = p.Index,
                                                                                              Type =
                                                                                          p.EntryType ==
                                                                                          EventLogEntryType.Error
                                                                                              ? "Error"
                                                                                              : p.EntryType ==
                                                                                                EventLogEntryType.
                                                                                                    Warning
                                                                                                    ? "Quota founded"
                                                                                                    : "Info",
                                                                                              Message = p.Message, Date = p.TimeWritten
                                                                                          }).ToList();
        }




        void Application_Idle(object sender, EventArgs e)
        {
            try
            {
                startToolStripMenuItem.Enabled = serviceController1.Status == ServiceControllerStatus.Stopped;
                toolStripButton3.Enabled = serviceController1.Status == ServiceControllerStatus.Stopped;
                toolStripButton4.Enabled = serviceController1.Status == ServiceControllerStatus.Running;
                stopToolStripMenuItem.Enabled = serviceController1.Status == ServiceControllerStatus.Running;
            }
            catch(InvalidOperationException ex)
            {
                MessageBox.Show("All application components wasn't installed. Please reinstall current application",
                                "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                _canClose = true;
                Close();
            }
        }

        void eventLog1_EntryWritten(object sender, System.Diagnostics.EntryWrittenEventArgs e)
        {
            //var item =
            //    new ListViewItem(new string[]
            //                         {
            //                             e.Entry.TimeWritten.ToShortDateString() + " " +
            //                             e.Entry.TimeWritten.ToShortTimeString(),
            //                             e.Entry.EntryType == EventLogEntryType.Error
            //                                 ? "Error"
            //                                 : e.Entry.EntryType == EventLogEntryType.Warning ? "Quota founded" : "Info"
            //                             , e.Entry.Message
            //                         });
            //if (e.Entry.EntryType == EventLogEntryType.Warning) item.BackColor = Color.DodgerBlue;
            //if (e.Entry.EntryType == EventLogEntryType.Error) item.BackColor = Color.Red;
            //lvLog.Items.Add(item);

            ReloadEvents();
            if (!Visible)
            {
                if (e.Entry.EntryType == EventLogEntryType.Error)
                    notifyIcon1.ShowBalloonTip(60000, "Checking Error", e.Entry.Message, ToolTipIcon.Error);
                if (e.Entry.EntryType == EventLogEntryType.Warning)
                {
                    notifyIcon1.ShowBalloonTip(180000, "Quota has been added", e.Entry.Message, ToolTipIcon.Info);
                    MessageBox.Show("Silvern Fern Quota has been added");
                }
            }
        }
        
        private void ServiceForm_Load(object sender, EventArgs e)
        {
            Text = Text + " (version: " + UpdateClass.GetApplicationVersion().ToString() + ")";
            var isNewVersionAvailible = UpdateClass.IsNewVersionAvailible();
            if (isNewVersionAvailible)
            {
                notifyIcon1.ShowBalloonTip(3000,"New Version", "New version availible. Download new version from the website",ToolTipIcon.Warning);
            }
            ReloadEvents();
        }

        private void ServiceForm_FormClosing(object sender, FormClosingEventArgs e)
        {
           if(!_canClose)
           {
               e.Cancel = true;
               Hide();
           }
        }

        private void requestsLogToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Show();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Exit();
        }

        private void settingsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            new SettingsForm().ShowDialog();
        }

        private void ServiceForm_Shown(object sender, EventArgs e)
        {
            Hide();
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            //if(lvLog.SelectedItems.Count>0)
            //{
            //    lvLog.Items.Remove(lvLog.SelectedItems[0]);
            //}
        }

        void Exit()
        {
            if (MessageBox.Show("Are you sure? Cheking process will be stoped.", "Application exit", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                _canClose = true;
                try
                {
                    if (serviceController1.Status == ServiceControllerStatus.Running)
                        StopService();
                }
                catch (InvalidOperationException ex)
                {
                    MessageBox.Show("All application components wasn't installed. Please reinstall current application",
                                    "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                Close();
            }
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            eventLog1.Clear();
            ReloadEvents();
            //lvLog.Items.Clear();
        }

        private void projectWebPageToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Process.Start("http://code.google.com/p/silver-fern-quota-check/");
        }

        private void giveUsFeedbackToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                Process.Start("mailto:silver.fern.bot@gmail.com?subject=Feedback");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Can not find default mail application. Please send it manually to silver.fern.bot@gmail.com", "Exception");
            }
        }

        private void dONATIONSToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Process.Start("http://code.google.com/p/silver-fern-quota-check/wiki/Donate");
        }

        void StartService()
        {
            serviceController1.Start();
            serviceController1.WaitForStatus(ServiceControllerStatus.Running);
        }

        void StopService()
        {
            serviceController1.Stop();
            serviceController1.WaitForStatus(ServiceControllerStatus.Stopped);
        }

        private void startToolStripMenuItem_Click(object sender, EventArgs e)
        {
            StartService();
        }

        private void stopToolStripMenuItem_Click(object sender, EventArgs e)
        {
            StopService();
        }

        private void toolStripButton9_Click(object sender, EventArgs e)
        {
            Exit();
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            StartService();
        }

        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            StopService();
        }

        private void toolStripButton8_Click(object sender, EventArgs e)
        {
            Process.Start("http://code.google.com/p/silver-fern-quota-check/wiki/Donate");
        }

        private void toolStripButton7_Click(object sender, EventArgs e)
        {
            try
            {
                Process.Start("mailto:silver.fern.bot@gmail.com?subject=Feedback");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Can not find default mail application. Please send it manually to silver.fern.bot@gmail.com", "Exception");
            }
        }

        private void toolStripButton6_Click(object sender, EventArgs e)
        {
            Process.Start("http://code.google.com/p/silver-fern-quota-check/");
        }

        private void toolStripButton5_Click(object sender, EventArgs e)
        {
            new SettingsForm().ShowDialog();
        }

        private void ServiceForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Idle -= new EventHandler(Application_Idle);
        }

        private void notifyIcon1_BalloonTipClicked(object sender, EventArgs e)
        {
            Show();
        }

        private void notifyIcon1_DoubleClick(object sender, EventArgs e)
        {
            Show();
        }

        private void dgvEvents_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if(e.RowIndex<0||e.ColumnIndex<0) return;
            if (dgvEvents.Rows[e.RowIndex].Cells["clmType"].Value.ToString() == "Error")
                e.CellStyle.BackColor = Color.Red;
            else if(dgvEvents.Rows[e.RowIndex].Cells["clmType"].Value.ToString() == "Quota founded")
                e.CellStyle.BackColor = Color.Green;
        }
    }
}
